<template>
  <view>
    <view class="pageClass">
      <up-popup :show="showReject" mode="bottom" overlayOpacity="1">
        <view class="btn-group">
          <text class="cancel" @click="$emit('closeFn')">取消</text>
          <text class="print" style="color: #3c9cff" @click="handlePrint"
            >打印</text
          >
        </view>
        <view class="popup-content">
          <view class="qrClassCode">
            <view class="titleClass">{{ titleName }}</view>
            <img :src="imgSrc" class="qrcode" />
          </view>
        </view>
      </up-popup>
    </view>
    <!-- <view class="pageClass">
      <up-popup :show="show_Reject" mode="bottom" closeOnClickOverlay>
        <view class="btn-group">
          <text class="cancel" @click="show_Reject = false">取消</text>
          <text class="print" style="color: #3c9cff" @click="handle_Sure"
            >确认打印</text
          >
        </view>
        <view class="popup-content">
          <view class="fenlun">
            <view class="titleClass">打印机：</view>
            <div @click="handleClick" class="xuanzhe">
              <text v-if="memberStore.PrinterName">{{
                memberStore.PrinterName
              }}</text>
              <text style="color: #ccc" v-else>请选择打印机</text>
            </div>
          </view>
        </view>
      </up-popup>
    </view> -->

    <view class="pageClass secondClass">
      <up-popup :show="show_sReject" mode="bottom" overlayOpacity="1">
        <view class="btn-group">
          <text class="cancel" @click="show_sReject = false">取消</text>
          <text class="print" style="color: #3c9cff" @click="handle_Sure"
            >确认打印</text
          >
        </view>
        <div class="popupClass">
          <view class="titleNamew">
            <text>已连接的打印机：</text>
            <text
              :style="{
                color: memberStore.PrinterName ? 'rgb(103, 194, 58)' : 'red',
              }"
              >{{ memberStore.PrinterName || "暂无连接打印机" }}</text
            >
          </view>
          <view class="searchclass">
            <up-search
              v-model.trim="searchName"
              placeholder="请输入打印机名称"
              :clearabled="true"
              :showAction="false"
              @search="handleSearch"
            />
            <view class="right">
              <up-button
                type="primary"
                @click="handleSearch"
                class="first"
                size="small"
                shape="circle"
                >搜索</up-button
              >
            </view>
          </view>
          <view class="caizhiOrGuige" v-show="printLists.length">
            <view
              v-for="item in printcompLists"
              :key="item.id"
              class="box"
              @click="handleLianjie(item.name)"
            >
              {{ item.name }}
            </view>
          </view>
          <up-empty
            mode="data"
            v-show="printcompLists.length == 0"
            text="暂无打印机"
          >
          </up-empty>
        </div>
      </up-popup>
    </view>
    <canvas
      :style="{
        width: canvasWidthResponsive + 'px',
        height: canvasHeightResponsive + 'px',
      }"
      id="myCanvas"
    >
    </canvas>
  </view>
</template>

<script setup>
import { usePrint } from "../../composables/print.js";
import { useMemberStore } from "@/stores/modules/member";
const deprops = defineProps(["imgSrc", "showReject", "titleName"]);
const {
  scanedPrinters,
  openPrinter,
  getSn,
  startJob,
  startDrawLabel,
  drawText,
  drawTextInRect,
  drawBarcode,
  drawQRCode,
  drawRectangle,
  drawLine,
  drawImage,
  endDrawLabel,
  print,
  didReadPrintCountInfo,
  didReadPrintErrorInfo,
  closePrinter,
} = usePrint();
const memberStore = useMemberStore();
// const show_Reject = ref(false);
const show_sReject = ref(false);
const printLists = ref([]); //搜索到的打印机数据
const searchName = ref("");
const canvasWidthResponsive = ref(320); //200dpi设备 标签物理宽度x8，300dpi设备 标签物理宽度x11.81
const canvasHeightResponsive = ref(200); //200dpi设备 标签物理高度x8，300dpi设备 标签物理高度x11.81
const printDataArr = ref([]); // 定义打印数据数组
const commitIndex = ref(0); // 当前打印数据索引
const instance = getCurrentInstance(); // 获取组件实例
const printcompLists = ref([]); //过滤后的打印机数据
const setTimes = ref([]); //定时器数组
const handlePrint = () => {
  searchName.value = "";
  uni.showToast({
    icon: "none",
    title: "正在搜索打印机，请稍后",
  });
  scanedPrinters((didGetScanedPrinters) => {
    let arr = didGetScanedPrinters.filter((items) => {
      return items.name && items.name.startsWith("B4");
    });
    console.log("didGetScanedPrinters", didGetScanedPrinters);
    console.log("B4打印机：", arr);
    printLists.value = arr;
    if (memberStore.PrinterName) {
      printcompLists.value = printLists.value.filter(
        (item) => item.name != memberStore.PrinterName
      );
    } else {
      printcompLists.value = printLists.value;
    }
    if (printLists.value.length == 0 && !memberStore.PrinterName) {
      return uni.showToast({
        icon: "none",
        title: "未搜索到打印机，请确认打印机是否开启",
      });
    }
    show_sReject.value = true;
    uni.hideLoading();
  });
};

const handleSearch = () => {
  let lists = [];
  if (searchName.value) {
    lists = printLists.value.filter((item) =>
      item.name.toLowerCase().includes(searchName.value.toLowerCase())
    );
  } else {
    lists = printLists.value;
  }
  printcompLists.value = lists.filter(
    (item) => item.name != memberStore.PrinterName
  );
};
const handleLianjie = (name) => {
  uni.showToast({
    icon: "none",
    title: "连接中，请稍后",
  });
  openPrinter(
    name,
    function () {
      uni.showToast({ icon: "success", title: "连接打印机成功" });
      console.log("连接打印机成功", name);

      let setId = setTimeout(() => {
        uni.hideLoading();
      }, 500);
      setTimes.value.push(setId);
      memberStore.PrinterName = name;
      handleSearch();
    },
    function () {
      memberStore.PrinterName = "";
      uni.showToast({
        icon: "none",
        title: "打印机连接失败，请确认打印机是否开机",
      });
      let setId = setTimeout(() => {
        uni.hideLoading();
      }, 500);
      setTimes.value.push(setId);
    }
  );
};
const downloadImage = (url) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url,
      success: (res) => {
        console.log("res:", res);
        resolve(res.tempFilePath);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
const generatePrintData = async (printType) => {
  if (printType === "text") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "text",
          json: {
            content: "content" + commitIndex.value,
            x: 2,
            y: 24,
            fontHeight: 3,
            rotation: 0,
            options: {},
          },
        },
      ],
    };
  }
  if (printType === "textRect") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "textRect",
          json: {
            content:
              "multiple content 多行文本|multiple content 多行文本|multiple content 多行文本",
            x: 2,
            y: 2,
            width: 46,
            height: 24,
            fontHeight: 3,
            rotation: 0,
            options: { lineModel: 3 },
          },
        },
      ],
    };
  } else if (printType === "barcode") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "barcode",
          json: {
            content: "12345678" + commitIndex.value,
            x: 2,
            y: 10,
            width: 24,
            height: 10,
            rotation: 0,
            fontSize: 3,
            fontHeight: 5,
            position: 0,
          },
        },
      ],
    };
  } else if (printType === "qrcode") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "qrcode",
          json: {
            content: "12345678" + commitIndex.value,
            x: 2,
            y: 10,
            width: 10,
            height: 10,
            rotation: 0,
            ecc: 2,
          },
        },
      ],
    };
  } else if (printType === "line") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "line",
          json: {
            x: 2,
            y: 10,
            width: 24,
            height: 0.25,
            rotation: 0,
          },
        },
      ],
    };
  } else if (printType === "rectangle") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "rectangle",
          json: {
            x: 2,
            y: 10,
            width: 24,
            height: 10,
            lineWidth: 0.25,
            isFilled: false,
            rotation: 0,
          },
        },
      ],
    };
  } else if (printType === "image") {
    let tempFilePath = "";
    try {
      // 下载图片
      tempFilePath = await downloadImage(deprops.imgSrc);
      console.log("tempFilePath", tempFilePath);
    } catch (error) {
      console.log("drawImage error", error);
    }
    return {
      width: 100,
      height: 80,
      rotation: 0,
      count: 1,
      element: [
        {
          type: "image",
          json: {
            path: tempFilePath,
            x: 0,
            y: 0,
            width: 100,
            height: 80,
            rotation: 0,
          },
        },
      ],
    };
  } else if (printType === "combination") {
    return {
      width: 50,
      height: 30,
      rotation: 0,
      element: [
        {
          type: "barcode",
          json: {
            content: "12345678" + commitIndex.value,
            x: 2,
            y: 12,
            width: 24,
            height: 10,
            rotation: 0,
            fontSize: 3,
            fontHeight: 5,
            position: 0,
          },
        },
        {
          type: "text",
          json: {
            content: "content" + commitIndex.value,
            x: 2,
            y: 5,
            fontHeight: 3,
            rotation: 0,
            options: {},
          },
        },
      ],
    };
  } else if (printType === "batch") {
    return [
      {
        width: 50,
        height: 30,
        rotation: 0,
        element: [
          {
            type: "barcode",
            json: {
              content: "123456781",
              x: 2,
              y: 12,
              width: 24,
              height: 10,
              rotation: 0,
              fontSize: 3,
              fontHeight: 5,
              position: 0,
            },
          },
          {
            type: "text",
            json: {
              content: "content1",
              x: 2,
              y: 5,
              fontHeight: 3,
              rotation: 0,
              options: {},
            },
          },
        ],
      },
      {
        width: 50,
        height: 30,
        rotation: 0,
        element: [
          {
            type: "barcode",
            json: {
              content: "123456782",
              x: 2,
              y: 12,
              width: 24,
              height: 10,
              rotation: 0,
              fontSize: 3,
              fontHeight: 5,
              position: 0,
            },
          },
          {
            type: "text",
            json: {
              content: "content2",
              x: 2,
              y: 5,
              fontHeight: 3,
              rotation: 0,
              options: {},
            },
          },
        ],
      },
    ];
  } else {
    alert("不支持的打印类型");
    return null;
  }
};
watch(
  () => deprops.imgSrc,
  async (newVal) => {
    if (newVal) {
      const printData = generatePrintData("image");
      if (Array.isArray(printData)) {
        printDataArr.value = printData;
      } else {
        printDataArr.value = [printData];
      }
    }
  }
);
const startPrint = () => {
  if (printDataArr.value.length <= commitIndex.value) return;
  const currentData = printDataArr.value[commitIndex.value];
  console.log("currentData", currentData);
  const {
    width: labelWidth,
    height: labelHeight,
    rotation,
    count,
  } = currentData;
  startDrawLabel("myCanvas", instance.proxy, labelWidth, labelHeight, rotation);
  currentData.element.forEach((element) => {
    if (element.type === "text") {
      drawText(
        element.json.content,
        element.json.x,
        element.json.y,
        element.json.fontHeight,
        element.json.rotation,
        element.json.options
      );
    } else if (element.type === "textRect") {
      drawTextInRect(
        element.json.content,
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.fontHeight,
        element.json.rotation,
        element.json.options
      );
    } else if (element.type === "barcode") {
      drawBarcode(
        element.json.content,
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.rotation,
        element.json.fontSize,
        element.json.fontHeight,
        element.json.position
      );
    } else if (element.type === "image") {
      drawImage(
        element.json.path,
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.rotation
      );
    } else if (element.type === "qrcode") {
      drawQRCode(
        element.json.content,
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.rotation
      );
    } else if (element.type === "rectangle") {
      drawRectangle(
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.lineWidth,
        element.json.isFilled,
        element.json.rotation
      );
    } else if (element.type === "line") {
      drawLine(
        element.json.x,
        element.json.y,
        element.json.width,
        element.json.height,
        element.json.rotation
      );
    }
  });
  endDrawLabel(() => {
    print(count, () => {
      commitIndex.value++;
      startPrint();
    });
  });
};
const handle_Sure = () => {
  getSn(async (res) => {
    if (res.code === -4) {
      uni.showToast({ title: "打印机未连接", icon: "none" });
      return;
    }
    if (printDataArr.value.length == 0) {
      uni.showToast({ title: "请添加打印内容", icon: "none" });
      return;
    }

    let totalCount = printDataArr.value.reduce((sum, item) => {
      return sum + item.count;
    }, 0);
    uni.showToast({ title: "开始打印" });
    didReadPrintCountInfo((res) => {
      uni.hideLoading();
      console.log(res.count);
    });
    didReadPrintErrorInfo((res) => {
      uni.hideLoading();
      console.log(res.errCode);
    });
    commitIndex.value = 0;
    startJob(1, 3, totalCount, () => {
      startPrint();
    });
  });
};
onUnmounted(() => {
  closePrinter();
  memberStore.PrinterName = "";
  setTimes.value.forEach((item) => {
    clearTimeout(item);
  });
  setTimes.value = [];
  console.log("unmounted11111111", memberStore.PrinterName);
});
</script>

<style lang="scss" scoped>
.qrClassCode {
  height: 600rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
  .qrcode {
    margin-bottom: 20rpx;
  }
}
.popupClass {
  display: flex;
  flex-direction: column;
  .caizhiOrGuige {
    height: 35vh;
    overflow-y: auto;
    .box {
      padding: 30rpx 0;
      text-align: center;
      border-bottom: 1px solid #ccc;
    }
  }
  .titleNamew {
    text-align: center;
    margin: 15px 0 10px;
  }
}
.xuanzhe {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
/* 将canvas元素置于屏幕左侧 */
canvas {
  /* 将canvas的左边缘定位到屏幕宽度的100%处，使其完全超出屏幕左侧显示区域 */
  position: fixed;
  left: 100%;
  /*新增属性，canvas背景白色，透明度为1，即不透明*/
  background: #fff;
  opacity: 1;
  /* 新增属性，canvas边框为1px，实线，黑色 ,用于调试时间查看canvas大小*/
  border: 1px solid #000;
}
</style>